package com.net.xpay.admin.controller.admin;

import com.net.common.model.ResultPagedList;
import com.net.xpay.admin.vo.ApiMonitorVo;
import com.net.xpay.common.manager.ApiMonitorManager;
import com.net.xpay.common.model.ApiMonitorAggModel;
import com.net.xpay.core.model.ApiMonitorSearchModel;
import com.net.xpay.core.utils.BeanCopierUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;

@RestController
@Slf4j
@RequestMapping("/admin/api-monitor")
@Api(tags = "后台/接口监控", description = "后台 接口监控")
public class AdminApiMonitorController {

    @Autowired
    private ApiMonitorManager apiMonitorManager;

    @ApiOperation("搜索接口监控数据")
    @PostMapping("/search")
    @ResponseBody
    @PreAuthorize("hasAnyRole('ADMIN', 'api-monitor::search')")
    public ResultPagedList<ApiMonitorVo> aggSearch(@RequestBody ApiMonitorSearchModel searchModel) {

        List<ApiMonitorAggModel> records = apiMonitorManager.aggSearch(searchModel);
        long count = apiMonitorManager.aggSearchCount(searchModel);
        List<ApiMonitorVo> vos = BeanCopierUtil.batchCopy(ApiMonitorAggModel.class, ApiMonitorVo.class, records);

        for (ApiMonitorVo vo : vos) {
            vo.setAvgReqCostTime(vo.getTotalReqCostTime() / vo.getReqCount());
            long reqSuccessCount = vo.getReqCount()-vo.getErrReqCount();
            if (vo.getErrReqCount() == 0){
                vo.setSuccessRate(new BigDecimal("100"));
            }else {
                vo.setSuccessRate(new BigDecimal(reqSuccessCount).multiply(new BigDecimal("100")).divide(new BigDecimal(vo.getReqCount()),2, RoundingMode.HALF_UP));
            }
        }
        return new ResultPagedList<>(vos, count, searchModel);
    }

}
